//package com.hbnu.system.service.impl;
//
//import com.baomidou.mybatisplus.core.toolkit.Wrappers;
//import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
//import cn.hutool.core.util.StrUtil;
//import com.hbnu.system.config.BaseException;
//import com.hbnu.system.model.entity.*;
//import com.hbnu.system.mapper.ProjectQualificationMapper;
//import com.hbnu.system.service.IProjectQualificationService;
//import com.hbnu.system.service.IProjectTypeService;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import java.util.List;
//import java.util.Objects;
//
//@Service
//public class ProjectQualificationServiceImpl extends ServiceImpl<ProjectQualificationMapper, Project_Qualification> implements IProjectQualificationService {
//    @Autowired
//    private IProjectTypeService iProjectTypeService;
//
//    @Autowired
//    private Tranproject_registrationServiceImpl tranproject_registrationService;
//
//    @Autowired
//    private Porproject_registrationServiceImpl porproject_registrationService;
//
//    @Override
//    public boolean addProject_Qualification(Project_Qualification project_qualification) {
//
//        if(project_qualification.getType1ID() != 3){
//            Tranproject_registration tranproject = tranproject_registrationService.getOne(Wrappers.lambdaQuery(Tranproject_registration.class)
//                    .eq(Tranproject_registration::getTRegistrationID, project_qualification.getProjectID()));
//            Porproject_registration porproject = porproject_registrationService.getOne(Wrappers.lambdaQuery(Porproject_registration.class)
//                    .eq(Porproject_registration::getPRegistrationID, project_qualification.getProjectID()));
//
//            System.out.println("====================");
//            System.out.println(tranproject);
//            System.out.println(porproject);
//
//            // 检查项目主键有效性
//            if (Objects.isNull(tranproject) && Objects.isNull(porproject)) {
//                throw new BaseException("项目主键编号有误!");
//            }
//
//            // 明确横向项目判断逻辑
//            if (!Objects.isNull(tranproject) && Objects.isNull(porproject)) {
//                System.out.println("进入横向项目逻辑");
//                Tranproject_registration p1=tranproject_registrationService.getTranproject(project_qualification.getProjectID());
//                if(p1.getProjectState().equals("待校级审核") || p1.getProjectState().equals("待院级审核") || p1.getProjectState().equals("审核通过")){
//                    throw new BaseException("该横向项目不能登记分数!");
//                }
//
//                // 验证到账经费
//                if (StrUtil.isBlank(String.valueOf(project_qualification.getFunds()))
//                        || StrUtil.isEmpty(String.valueOf(project_qualification.getFunds()))) {
//                    throw new BaseException("到账经费未填写!");
//                }
//
//                // 获取项目类型
//                Project_Type project_type = iProjectTypeService.getOne(
//                        Wrappers.lambdaQuery(Project_Type.class)
//                                .eq(Project_Type::getType1ID, project_qualification.getType1ID())
//                                .eq(Project_Type::getType2ID, project_qualification.getType2ID())
//                );
//
//                // 设置项目类型信息
//                project_qualification.setProjectType1(project_type.getProjectType1());
//                project_qualification.setProjectType2(project_type.getProjectType2());
//
//                // 计算分值
//                float value = project_type.getValue() * project_qualification.getFunds();
//                value = Math.round(value * 100) / 100f;
//
//                project_qualification.setFinalValue(value);
//                tranproject.setScore(value);
//                tranproject_registrationService.updateTranproject(tranproject);
//
//                return baseMapper.insert(project_qualification) == 1;
//            }else {
//                // 纵向项目逻辑（只有满足纵向条件才会进入）
//                System.out.println("进入纵向项目逻辑");
//                Porproject_registration p1=porproject_registrationService.getPorproject(project_qualification.getProjectID());
//                if(p1.getProjectState().equals("待校级审核") || p1.getProjectState().equals("待院级审核") || p1.getProjectState().equals("审核通过")){
//                    throw new BaseException("该纵向项目不能登记分数!");
//                }
//                // 验证纵向项目必填字段
//                if (StrUtil.isBlank(String.valueOf(project_qualification.getFunds()))
//                        || StrUtil.isEmpty(String.valueOf(project_qualification.getFunds()))) {
//                    throw new BaseException("到账经费未填写!");
//                }
//                if (StrUtil.isBlank(project_qualification.getInstructive())
//                        || StrUtil.isEmpty(project_qualification.getInstructive())) {
//                    throw new BaseException("请确认是否为指导性项目!");
//                }
//                if (StrUtil.isBlank(project_qualification.getDiscipline())
//                        || StrUtil.isEmpty(project_qualification.getDiscipline())) {
//                    throw new BaseException("请选择项目类别!");
//                }
//
//                // 获取项目类型
//                Project_Type project_type = iProjectTypeService.getOne(
//                        Wrappers.lambdaQuery(Project_Type.class)
//                                .eq(Project_Type::getType1ID, project_qualification.getType1ID())
//                                .eq(Project_Type::getType2ID, project_qualification.getType2ID())
//                );
//
//                // 设置项目类型信息
//                project_qualification.setProjectType1(project_type.getProjectType1());
//                project_qualification.setProjectType2(project_type.getProjectType2());
//
//                // 计算纵向项目分值
//                float value = project_type.getValue() * project_qualification.getFunds();
//                if (project_qualification.getInstructive().equals("是")) {
//                    value *= 0.5;
//                }
//                if (project_qualification.getDiscipline().equals("自然科学类")) {
//                    value += 20 * project_qualification.getFunds();
//                } else {
//                    value += 30 * project_qualification.getFunds();
//                }
//                porproject.setScore(value);
//                project_qualification.setFinalValue(value);
//
//                porproject_registrationService.updatePorproject(porproject);
//                return baseMapper.insert(project_qualification) == 1;
//            }
//        }else {
//                return true;
//        }
//    }
//
//    @Override
//    public boolean deleteProject_Qualification(String ProjectQualificationID) {
//        Project_Qualification project_qualification = baseMapper.selectOne(Wrappers.lambdaQuery(Project_Qualification.class)
//                .eq(Project_Qualification::getProjectQualificationID, ProjectQualificationID));
//
//        if(Objects.isNull(project_qualification)){
//            throw new BaseException("量化编号有误");
//        }
//
//        if(project_qualification.getType1ID() == 1){ // 取纵向项目
//            Porproject_registration p1=porproject_registrationService.getPorproject(project_qualification.getProjectID());
//            if(p1.getProjectState().equals("待校级审核") || p1.getProjectState().equals("待院级审核") || p1.getProjectState().equals("审核通过")){
//                throw new BaseException("该纵向项目不能删除分数!");
//            }
//            Porproject_registration porproject = porproject_registrationService.getPorproject(project_qualification.getProjectID());
//            porproject.setScore(0);
//            porproject_registrationService.updateById(porproject);
//        }else if(project_qualification.getType1ID() == 2){ //取横向项目
//            Tranproject_registration p1=tranproject_registrationService.getTranproject(project_qualification.getProjectID());
//            if(p1.getProjectState().equals("待校级审核") || p1.getProjectState().equals("待院级审核") || p1.getProjectState().equals("审核通过")){
//                throw new BaseException("该横向项目不能删除分数!");
//            }
//            Tranproject_registration tranproject = tranproject_registrationService.getTranproject(project_qualification.getProjectID());
//            tranproject.setScore(0);
//            tranproject_registrationService.updateById(tranproject);
//        }else {
//
//        }
//
//        return baseMapper.deleteById(project_qualification) == 1;
//
//    }
//
//    @Override
//    public List<Project_Qualification> getOneProject_Qualification(String ProjectID) {
//        Tranproject_registration tranproject = tranproject_registrationService.getOne(Wrappers.lambdaQuery(Tranproject_registration.class)
//                .eq(Tranproject_registration::getTRegistrationID, ProjectID));
//        Porproject_registration porproject = porproject_registrationService.getOne(Wrappers.lambdaQuery(Porproject_registration.class)
//                .eq(Porproject_registration::getPRegistrationID, ProjectID));
//        if(Objects.isNull(tranproject) && Objects.isNull(porproject)){ //既搜索不到纵向也搜索不到横向
//            throw new BaseException("项目主键编号有误!");
//        }
//
//        List<Project_Qualification> project_qualifications = baseMapper.selectList(Wrappers.lambdaQuery(Project_Qualification.class)
//                .eq(Project_Qualification::getProjectID, ProjectID));
//
//        return project_qualifications;
//
//    }
//}


package com.hbnu.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.system.config.BaseException;
import com.hbnu.system.mapper.ProjectQualificationMapper;
import com.hbnu.system.model.context.BaseContext;
import com.hbnu.system.model.entity.*;
import com.hbnu.system.service.*;
import com.hbnu.system.utils.CheckRoleUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Objects;

@Service
public class ProjectQualificationServiceImpl extends ServiceImpl<ProjectQualificationMapper, Project_Qualification> implements IProjectQualificationService {

    @Autowired
    private IProjectTypeService projectTypeService;
    @Autowired
    private Tranproject_registrationServiceImpl tranprojectRegistrationService; // 横向项目服务
    @Autowired
    private Porproject_registrationServiceImpl porprojectRegistrationService;   // 纵向项目服务
    @Autowired
    private IUserService iUserService;
    @Autowired
    private CheckRoleUtil checkRoleUtil;
    
    @Autowired
    private PorprojectauthorService porprojectauthorService;
    
    @Autowired
    private TranprojectauthorService tranprojectauthorService; 

    @Override
    public boolean addProject_Qualification(Project_Qualification qualification) {

        validateProjectExistence(qualification.getProjectID()); // 验证项目存在

        if (qualification.getType1ID() == 1) { // 纵向项目
            return handleVerticalProject(qualification);
        } else if (qualification.getType1ID() == 2) { // 横向项目
            return handleHorizontalProject(qualification);
        } else {
            return true; // 其他类型暂不处理
        }
    }

    // 纵向项目处理逻辑
    private boolean handleVerticalProject(Project_Qualification qualification) {
        Porproject_registration porProject = getPorProject(qualification.getProjectID());

        checkRoleUtil.checkPermissionProject(porProject.getProjectState());
        if(qualification.getManualScoreMode()=="true"){
            System.out.println("true");
            porProject.setScore(qualification.getFinalValue());
            porProject.setNotes(qualification.getNote());
        }else {
            System.out.println("false");
            validateVerticalRequiredFields(qualification); // 验证必填字段
            Project_Type typeConfig = getProjectType(qualification); // 获取类型配置

            // 计算分值：级别分（配置值） + 金额分（自然科学20/万，人文社科30/万）
            float levelScore = typeConfig.getValue();
            float fundScore = qualification.getDiscipline().equals("自然科学") ? 20 : 30;
            float finalValue = levelScore + fundScore * qualification.getFunds();

            int type2Id = typeConfig.getType2ID();
            if (type2Id == 19) {
                finalValue= qualification.getFunds() * 30;
            }

            // 赋值并更新
            qualification.setProjectType1(typeConfig.getProjectType1());
            qualification.setProjectType2(typeConfig.getProjectType2());
            qualification.setFinalValue(roundTwoDecimal(finalValue));

            porProject.setScore(qualification.getFinalValue()); // 更新纵向项目分数
        }
        boolean updateSuccess = porprojectRegistrationService.updateById(porProject); // 纵向服务更新
        boolean insertSuccess = baseMapper.insert(qualification) == 1;

        String Pscore = "0.00";
        // 9. 修改著作作者的个人得分
        System.out.println("porProject="+porProject);
        String porprojectid=porProject.getPRegistrationID();
        System.out.println("porprojectid="+porprojectid);
        List<Porprojectauthor> porprojectauthorList = porprojectauthorService.porprojectauthor(porprojectid);
        System.out.println("porprojectauthorList="+porprojectauthorList);
        String userId = BaseContext.getCurrentId();
        User user = iUserService.getById(userId);
        if (porprojectauthorList != null && !porprojectauthorList.isEmpty()) {
            boolean shouldUpdate = true;
            if (porprojectauthorList.size() == 1) {
                Porprojectauthor soleAuthor = porprojectauthorList.get(0);
                if (Objects.equals(soleAuthor.getUserAccount(), user.getAccount())) {
                    shouldUpdate= false;
                }
            }
            // 执行更新操作
            if (shouldUpdate) {
                for (Porprojectauthor author : porprojectauthorList) {
                    porprojectauthorService.updateporprojectAuthor(author);
                }
            }
        }
        
        return updateSuccess && insertSuccess;
    }


    private boolean handleHorizontalProject(Project_Qualification qualification) {

        // 1. 获取横向项目基础信息
        Tranproject_registration tranProject = getTranProject(qualification.getProjectID());
        System.out.println("tran=" + tranProject);
        checkRoleUtil.checkPermissionProject(tranProject.getProjectState()); // 状态校验

        if(qualification.getManualScoreMode()=="true"){
            tranProject.setScore(qualification.getFinalValue());
            tranProject.setNotes(qualification.getNote());
        }else{
            // 2. 验证必填字段（补充合同金额、审批时间的非空校验）
            validateHorizontalRequiredFields(qualification);
            if (tranProject.getContractFunds() == null || tranProject.getApprovalTime() == null) {
                throw new BaseException("项目合同金额或审批时间未填写，无法计算分数");
            }

            // 3. 获取项目类型配置（从projecttype表）
            Project_Type typeConfig = getProjectType(qualification);
            int type2Id = typeConfig.getType2ID();

            // 4. 提取项目扩展属性（关键修改：Date转LocalDate）
            Float approvedFunds;
            try {
                approvedFunds = Float.parseFloat(tranProject.getContractFunds()); // 合同金额（立项金额）
            } catch (NumberFormatException e) {
                throw new BaseException("合同金额格式错误，需为数值类型");
            }

            LocalDate projectDate = tranProject.getApprovalTime();
            String fundSource = tranProject.getProjectUnit(); // 经费来源（项目承担单位）


            // 5. 分场景计算分值
            float finalValue;

            // 计算分值：级别分（配置值） + 金额分（自然科学20/万，人文社科30/万）
            float levelScore = typeConfig.getValue();
            switch (type2Id) {
                // ===== 场景1：2025年前立项的教育部产学合作项目（Type2ID=14）=====
                case 18:
                    if (projectDate != null && projectDate.isBefore(LocalDate.of(2025, 1, 1))) {
                        finalValue = qualification.getFunds() * 60; // 旧规则：每万元60分
                    } else {
                        finalValue = calculateIndustryProjectScore(typeConfig, qualification); // 2025后：项目分+经费分
                    }
                    break;

                // ===== 场景2：校级产学合作（16）=====
                case 16:
                    if (approvedFunds == null) {
                        throw new BaseException("项目未配置【立项金额】，无法计算校级产学合作协同育人项目");
                    }
                    if (qualification.getFunds() <= approvedFunds) {
                        finalValue = qualification.getFunds() * 60; // 未超额：60分/万
                    } else {
                        float excess = qualification.getFunds() - approvedFunds;
                        finalValue = approvedFunds * 60 + excess * 30; // 超额部分：30分/万
                    }
                    break;
                // ===== 场景5：教育厅认定省级产学合作（2025年后）（13）=====
                case 13:
                    if (approvedFunds == null) {
                        throw new BaseException("项目未配置【立项金额】，无法计算教育厅认定省级产学合作（2025年后）项目");
                    }
                    if (qualification.getFunds() <= approvedFunds) {
                        finalValue = levelScore+qualification.getFunds() * 60; // 未超额：60分/万
                    } else {
                        float excess = qualification.getFunds() - approvedFunds;
                        finalValue = levelScore+approvedFunds * 60 + excess * 30; // 超额部分：30分/万
                    }
                    break;
                //教育部认定优秀产学合作（2025年后）
                case 14:
                    if (approvedFunds == null) {
                        throw new BaseException("项目未配置【立项金额】，无法计算教育部认定优秀产学合作（2025年后）项目");
                    }
                    if (qualification.getFunds() <= approvedFunds) {
                        finalValue = levelScore + qualification.getFunds() * 60; // 未超额：60分/万
                    } else {
                        float excess = qualification.getFunds() - approvedFunds;
                        finalValue = levelScore + approvedFunds * 60 + excess * 30; // 超额部分：30分/万
                    }
                    break;
                //或地市级揭榜制（17）
                case 17:
                    if (approvedFunds == null) {
                        throw new BaseException("项目未配置【立项金额】，无法计算地市级揭榜制科技项目分数");
                    }
                    if (qualification.getFunds() <= approvedFunds) {
                        finalValue = qualification.getFunds() * 60; // 未超额：60分/万
                    } else {
                        float excess = qualification.getFunds() - approvedFunds;
                        finalValue = approvedFunds * 60 + excess * 30; // 超额部分：30分/万
                    }
                    break;

                // ===== 场景3：外校纵向项目划拨经费（来源标记）=====
                default:
                    if ("外校划拨".equals(fundSource)) {
                        finalValue = qualification.getFunds() * 30; // 横向标准：30分/万
                    }
                    // ===== 场景4：普通横向 / 2025后产学合作 =====
                    else if (isIndustryProject(type2Id)) {
                        finalValue = calculateIndustryProjectScore(typeConfig, qualification);
                    } else {
                        finalValue = typeConfig.getValue() * qualification.getFunds(); // 普通横向（需数据库配置Value=30）
                    }
            }


            // 6. 赋值并持久化
            qualification.setProjectType1(typeConfig.getProjectType1());
            qualification.setProjectType2(typeConfig.getProjectType2());
            qualification.setFinalValue(roundTwoDecimal(finalValue));

            tranProject.setScore(qualification.getFinalValue());
            System.out.println("tranProject===="+tranProject);
        }

        boolean updateSuccess = tranprojectRegistrationService.updateById(tranProject);
        boolean insertSuccess = baseMapper.insert(qualification) == 1;

        String Pscore = "0.00";
        // 9. 修改著作作者的个人得分
        String troid=tranProject.getTRegistrationID();
        List<Tranprojectauthor> tranprojectauthorList = tranprojectauthorService.tranprojectauthor(troid);
        System.out.println("tranprojectauthorList===="+tranprojectauthorList);
        String userId = BaseContext.getCurrentId();
        User user = iUserService.getById(userId);
        if (tranprojectauthorList != null && !tranprojectauthorList.isEmpty()) {
            boolean shouldUpdate = true;
            if (tranprojectauthorList.size() == 1) {
                Tranprojectauthor soleAuthor = tranprojectauthorList.get(0);
                if (Objects.equals(soleAuthor.getUserAccount(), user.getAccount())) {
                    shouldUpdate= false;
                }
            }
            // 执行更新操作
            if (shouldUpdate) {
                for (Tranprojectauthor author : tranprojectauthorList) {
                    tranprojectauthorService.updatetranprojectAuthor(author);
                }
            }
        }

        return updateSuccess && insertSuccess;
    }

    // ------------------- 辅助方法 -------------------

    private void validateVerticalRequiredFields(Project_Qualification qualification) {
        if (StrUtil.isBlank(String.valueOf(qualification.getFunds()))) {
            throw new BaseException("到账经费未填写!");
        }
        if (StrUtil.isBlank(qualification.getDiscipline())) {
            throw new BaseException("请选择项目类别!");
        }
    }

    private void validateHorizontalRequiredFields(Project_Qualification qualification) {
        if (StrUtil.isBlank(String.valueOf(qualification.getFunds()))) {
            throw new BaseException("到账经费未填写!");
        }
    }

    private void validateProjectExistence(String projectId) {
        Tranproject_registration tran = tranprojectRegistrationService.getOne(Wrappers.lambdaQuery(Tranproject_registration.class).eq(Tranproject_registration::getTRegistrationID, projectId));
        Porproject_registration por = porprojectRegistrationService.getOne(Wrappers.lambdaQuery(Porproject_registration.class).eq(Porproject_registration::getPRegistrationID, projectId));
        if (Objects.isNull(tran) && Objects.isNull(por)) {
            throw new BaseException("项目主键编号有误!");
        }
    }


    private Porproject_registration getPorProject(String projectId) {
        return porprojectRegistrationService.getOne(Wrappers.lambdaQuery(Porproject_registration.class).eq(Porproject_registration::getPRegistrationID, projectId));
    }

    private Tranproject_registration getTranProject(String projectId) {
        return tranprojectRegistrationService.getOne(Wrappers.lambdaQuery(Tranproject_registration.class).eq(Tranproject_registration::getTRegistrationID, projectId));
    }

    private Project_Type getProjectType(Project_Qualification qualification) {
        Project_Type projectType = projectTypeService.getOne(Wrappers.lambdaQuery(Project_Type.class)
                .eq(Project_Type::getType1ID, qualification.getType1ID())
                .eq(Project_Type::getType2ID, qualification.getType2ID()));
        if (projectType == null) {
            throw new BaseException("未找到对应的项目类型配置");
        }
        return projectType;
    }

    private float calculateIndustryProjectScore(Project_Type typeConfig, Project_Qualification qualification) {
        float projectScore = typeConfig.getValue(); // 项目分（厅级/省部级，从配置取）
        float fundScore = qualification.getFunds() * 60; // 经费分固定60/万
        return projectScore + fundScore;
    }

    private boolean isIndustryProject(int type2Id) {
        return type2Id == 13 || type2Id == 14; // 省级/教育部产学合作项目
    }

    private float roundTwoDecimal(float value) {
        return Math.round(value * 100) / 100f;
    }

    // ------------------- 删除逻辑 -------------------
    @Override
    public boolean deleteProject_Qualification(String qualificationId) {
        Project_Qualification qualification = baseMapper.selectOne(Wrappers.lambdaQuery(Project_Qualification.class)
                .eq(Project_Qualification::getProjectQualificationID, qualificationId));
        if (Objects.isNull(qualification)) {
            throw new BaseException("量化编号有误");
        }


        // 按类型清除分数
        if (qualification.getType1ID() == 1) { // 纵向
            Porproject_registration porProject = getPorProject(qualification.getProjectID());
            checkRoleUtil.checkPermissionProject(porProject.getProjectState());
            porProject.setScore(0);

            System.out.println("porProject="+porProject);
            porprojectRegistrationService.updateById(porProject);

//            String Pscore = "0.00";
            // 9. 修改著作作者的个人得分
            String porprojectid=porProject.getPRegistrationID();
            List<Porprojectauthor> porprojectauthorList = porprojectauthorService.porprojectauthor(porprojectid);
            System.out.println("porprojectauthorList="+porprojectauthorList);
            String userId = BaseContext.getCurrentId();
            User user = iUserService.getById(userId);
            if (porprojectauthorList != null && !porprojectauthorList.isEmpty()) {
                boolean shouldUpdate = true;
                if (porprojectauthorList.size() == 1) {
                    Porprojectauthor soleAuthor = porprojectauthorList.get(0);
                    if (Objects.equals(soleAuthor.getUserAccount(), user.getAccount())) {
                        System.out.println("1=1=11=");
                        shouldUpdate= false;
                    }
                }
                // 执行更新操作
                if (shouldUpdate) {
                    for (Porprojectauthor author : porprojectauthorList) {
                        System.out.println("==============");
                        porprojectauthorService.updateporprojectAuthor(author);
                    }
                }
            }
            porprojectRegistrationService.updateById(porProject);
        } else if (qualification.getType1ID() == 2) { // 横向
            Tranproject_registration tranProject = getTranProject(qualification.getProjectID());
            checkRoleUtil.checkPermissionProject(tranProject.getProjectState());
            tranProject.setScore(0);
            
            // 确保所有字符串字段不为null，避免更新时出现空指针异常
            ensureStringFieldsNotNull(tranProject);

            tranprojectRegistrationService.updateById(tranProject);

            // 9. 修改著作作者的个人得分
            String troid=tranProject.getTRegistrationID();
            List<Tranprojectauthor> tranprojectauthorList = tranprojectauthorService.tranprojectauthor(troid);
            String userId = BaseContext.getCurrentId();
            User user = iUserService.getById(userId);
            if (tranprojectauthorList != null && !tranprojectauthorList.isEmpty()) {
                boolean shouldUpdate = true;
                if (tranprojectauthorList.size() == 1) {
                    Tranprojectauthor soleAuthor = tranprojectauthorList.get(0);
                    if (Objects.equals(soleAuthor.getUserAccount(), user.getAccount())) {
                        shouldUpdate= false;
                    }
                }
                // 执行更新操作
                if (shouldUpdate) {
                    for (Tranprojectauthor author : tranprojectauthorList) {
                        tranprojectauthorService.updatetranprojectAuthor(author);
                    }
                }
            }
            
            // 再次确保所有字符串字段不为null
            ensureStringFieldsNotNull(tranProject);
            tranprojectRegistrationService.updateById(tranProject);
        }

        return baseMapper.deleteById(qualification) == 1;
    }

    /**
     * 确保横向项目实体的所有字符串字段不为null
     */
    private void ensureStringFieldsNotNull(Tranproject_registration tranProject) {
        if (tranProject.getProjectSourceUnitId() == null) {
            tranProject.setProjectSourceUnitId("");
        }
        if (tranProject.getSourceEnterpriseCategory() == null) {
            tranProject.setSourceEnterpriseCategory("");
        }
        if (tranProject.getProjectSourceUnit() == null) {
            tranProject.setProjectSourceUnit("");
        }
        if (tranProject.getNationalEconomy() == null) {
            tranProject.setNationalEconomy("");
        }
        if (tranProject.getNationalEconomyId() == null) {
            tranProject.setNationalEconomyId("");
        }
        if (tranProject.getDisciplineClassfi() == null) {
            tranProject.setDisciplineClassfi("");
        }
        if (tranProject.getActivityType() == null) {
            tranProject.setActivityType("");
        }
        if (tranProject.getProjectSourse() == null) {
            tranProject.setProjectSourse("");
        }
        if (tranProject.getOrganizationForm() == null) {
            tranProject.setOrganizationForm("");
        }
        if (tranProject.getCooperaForm() == null) {
            tranProject.setCooperaForm("");
        }
        if (tranProject.getSocialEconomy() == null) {
            tranProject.setSocialEconomy("");
        }
        if (tranProject.getSourceUnitType() == null) {
            tranProject.setSourceUnitType("");
        }
        if (tranProject.getSecondUnit() == null) {
            tranProject.setSecondUnit("");
        }
    }

    // ------------------- 查询逻辑 -------------------
    @Override
    public List<Project_Qualification> getOneProject_Qualification(String projectId) {
        validateProjectExistence(projectId);
        return baseMapper.selectList(Wrappers.lambdaQuery(Project_Qualification.class)
                .eq(Project_Qualification::getProjectID, projectId));
    }


}